import Actions from './actions'
import { setStorage, getStorage } from '@/utils/storage'

const initState = {
  userId: '', // 我的用户ID
  role: '',
  roomInfo: null,
  openAudio: true,
  openCamera: true,
}

const reducer = (state = initState, action) => {
  switch (action.type) {
    case Actions.SET_USER_ID:
      return {
        ...state,
        userId: action.userId
      }
    case Actions.SET_ROLE:
      return {
        ...state,
        role: action.role
      }
    case Actions.SET_MEDIA_STATUS:
      return {
        ...state,
        openAudio: action.openAudio !== undefined ? action.openAudio : state.openAudio,
        openCamera: action.openCamera !== undefined ? action.openCamera : state.openCamera
      }
    case Actions.SET_ROOM:
      return {
        ...state,
        roomInfo: action.roomInfo
      }
    case Actions.SET_USER_STREAM:
      /* 生成新的users数据，把streamId存储给对应的user, 触发roomInfo修改 */
      const users = state.roomInfo.users.map(user => {
        if (user.id === action.userId) {
          return {
            ...user,
            streamId: action.streamId
          }
        }
        return user
      })

      return {
        ...state,
        roomInfo: {
          ...state.roomInfo,
          users
        }
      }
    default:
      return state
  }
}

export default reducer
